package cn.anxingongyou.anxin.service.impl;

import cn.anxingongyou.anxin.entity.*;
import cn.anxingongyou.anxin.mapper.UserEmployerInfoMapper;
import cn.anxingongyou.anxin.mapper.UserParentMapper;
import cn.anxingongyou.anxin.mapper.UserWorkerInfoMapper;
import cn.anxingongyou.anxin.service.LoginService;
import cn.anxingongyou.anxin.utils.AES;
import cn.anxingongyou.anxin.utils.HttpUtil;
import cn.anxingongyou.anxin.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    private final UserParentMapper userParentMapper;
    private final UserWorkerInfoMapper userWorkerInfoMapper;
    private final UserEmployerInfoMapper userEmployerInfoMapper;

    @Autowired
    public LoginServiceImpl(UserParentMapper userParentMapper, UserWorkerInfoMapper userWorkerInfoMapper, UserEmployerInfoMapper userEmployerInfoMapper) {
        this.userParentMapper = userParentMapper;
        this.userWorkerInfoMapper = userWorkerInfoMapper;
        this.userEmployerInfoMapper = userEmployerInfoMapper;
    }

    /***
     * 获取openid
     * @param phoneEncryptedData
     * @param appID
     * @param appSecret
     * @return
     * @throws IOException
     */
    @Override
    public OpenIdJson getOpenID(PhoneEncryptedData phoneEncryptedData,String appID,String appSecret) throws IOException {
        //获取OpenId
        String result = "";
        try{//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + appID + "&secret="
                            + appSecret + "&js_code="
                            + phoneEncryptedData.getCode()
                            + "&grant_type=authorization_code", null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        OpenIdJson openIdJson = mapper.readValue(result,OpenIdJson.class);
        return openIdJson;
    }

    /***
     * 解密获取手机号
     * @param phoneEncryptedData
     * @param openIdJson
     * @return
     * @throws IOException
     */
    @Override
    public Map<String, Object> getPhoneMap(PhoneEncryptedData phoneEncryptedData, OpenIdJson openIdJson) throws IOException {
        String phone = AES.wxDecrypt(phoneEncryptedData.getEncryptedData(),openIdJson.getSession_key(),phoneEncryptedData.getIv());

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = null;
        map = objectMapper.readValue(phone, Map.class);
        return map;
    }

    /***
     * 添加用户
     * @param phoneMap
     * @param openIdJson
     * @param userWorkerInfo
     * @return
     */
    @Override
    public Map<String, Object> addOrGetUser(Map<String,Object> phoneMap, OpenIdJson openIdJson, UserWorkerInfo userWorkerInfo) {

        Map<String, Object> res = new HashMap<>();
        UserEmployerInfo userEmployerInfo = new UserEmployerInfo();
        UserParent userParent = new UserParent();

        userParent.setPhone(phoneMap.get("phoneNumber").toString());
        List<UserParent> list = userParentMapper.select(userParent);

        if(list.size() > 0) {
            // 数据库已经注册
            userParent = list.get(0);
            res.put("userParent", userParent);
            userEmployerInfo = userEmployerInfoMapper.selectByPrimaryKey(userParent.getUserEmployerId());
            res.put("userEmployerInfo", userEmployerInfo);
            userWorkerInfo = userWorkerInfoMapper.selectByPrimaryKey(userParent.getUserWorkerId());
            res.put("userWorkerInfo", userWorkerInfo);
        }else{
            // 数据库未注册
            // 添加用户父表数据
            userParent.setOpenid(openIdJson.getOpenid());
            userParent.setCreated(new Date());
            userParent.setUpdated(new Date());
            userParentMapper.insertSelective(userParent);

            // 添加求职者信息
            userWorkerInfo.setUserPid(userParent.getId()); // 设置父表主键
            userWorkerInfo.setPhone(phoneMap.get("phoneNumber").toString());
            userWorkerInfo.setCreated(new Date());
            userWorkerInfo.setUpdated(new Date());
            userWorkerInfoMapper.insertSelective(userWorkerInfo);

            // 添加招聘者信息
            userEmployerInfo.setUserPid(userParent.getId()); // 设置父表主键
            userEmployerInfo.setPhone(phoneMap.get("phoneNumber").toString());
            userEmployerInfo.setLogo(userWorkerInfo.getAvatar());
            userEmployerInfo.setEnterpriseName(userWorkerInfo.getUsername());
            userEmployerInfo.setCreated(new Date());
            userEmployerInfo.setUpdated(new Date());
            userEmployerInfoMapper.insertSelective(userEmployerInfo);

            // 更新父表的内容
            userParent.setUserWorkerId(userWorkerInfo.getId());
            userParent.setUserEmployerId(userEmployerInfo.getId());
            userParent.setUpdated(new Date());
            userParentMapper.updateByPrimaryKeySelective(userParent);

            res.put("userParent", userParent);
            res.put("userEmployerInfo", userEmployerInfo);
            res.put("userWorkerInfo", userWorkerInfo);
        }
        return Result.<Map<String, Object>>instance(200,"登录成功",res).toJsonMap();
    }

    @Override
    public Map<String, Object> getUserInfo(Long id) {
        Map<String, Object> res = new HashMap<>();
        UserParent userParent = userParentMapper.selectByPrimaryKey(id);
        UserEmployerInfo userEmployerInfo = userEmployerInfoMapper.selectByPrimaryKey(id);
        UserWorkerInfo userWorkerInfo = userWorkerInfoMapper.selectByPrimaryKey(id);
        res.put("userParent", userParent);
        res.put("userEmployerInfo", userEmployerInfo);
        res.put("userWorkerInfo", userWorkerInfo);
        return Result.<Map<String, Object>>instance(200,"查询成功",res).toJsonMap();
    }


}
